/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.SubcontarctorResources;
import pojos.Subcontarctors;
import pojos.SourceCode;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author A7med Kotb
 */
public class SubcontarctorResourcesJpaController implements Serializable {

    public SubcontarctorResourcesJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(SubcontarctorResources subcontarctorResources) throws RollbackFailureException, Exception {
        if (subcontarctorResources.getSourceCodeCollection() == null) {
            subcontarctorResources.setSourceCodeCollection(new ArrayList<SourceCode>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Subcontarctors subcontractor = subcontarctorResources.getSubcontractor();
            if (subcontractor != null) {
                subcontractor = em.getReference(subcontractor.getClass(), subcontractor.getSubId());
                subcontarctorResources.setSubcontractor(subcontractor);
            }
            Collection<SourceCode> attachedSourceCodeCollection = new ArrayList<SourceCode>();
            for (SourceCode sourceCodeCollectionSourceCodeToAttach : subcontarctorResources.getSourceCodeCollection()) {
                sourceCodeCollectionSourceCodeToAttach = em.getReference(sourceCodeCollectionSourceCodeToAttach.getClass(), sourceCodeCollectionSourceCodeToAttach.getScId());
                attachedSourceCodeCollection.add(sourceCodeCollectionSourceCodeToAttach);
            }
            subcontarctorResources.setSourceCodeCollection(attachedSourceCodeCollection);
            em.persist(subcontarctorResources);
            if (subcontractor != null) {
                subcontractor.getSubcontarctorResourcesCollection().add(subcontarctorResources);
                subcontractor = em.merge(subcontractor);
            }
            for (SourceCode sourceCodeCollectionSourceCode : subcontarctorResources.getSourceCodeCollection()) {
                SubcontarctorResources oldSubcontResNameOfSourceCodeCollectionSourceCode = sourceCodeCollectionSourceCode.getSubcontResName();
                sourceCodeCollectionSourceCode.setSubcontResName(subcontarctorResources);
                sourceCodeCollectionSourceCode = em.merge(sourceCodeCollectionSourceCode);
                if (oldSubcontResNameOfSourceCodeCollectionSourceCode != null) {
                    oldSubcontResNameOfSourceCodeCollectionSourceCode.getSourceCodeCollection().remove(sourceCodeCollectionSourceCode);
                    oldSubcontResNameOfSourceCodeCollectionSourceCode = em.merge(oldSubcontResNameOfSourceCodeCollectionSourceCode);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(SubcontarctorResources subcontarctorResources) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            SubcontarctorResources persistentSubcontarctorResources = em.find(SubcontarctorResources.class, subcontarctorResources.getSubResId());
            Subcontarctors subcontractorOld = persistentSubcontarctorResources.getSubcontractor();
            Subcontarctors subcontractorNew = subcontarctorResources.getSubcontractor();
            Collection<SourceCode> sourceCodeCollectionOld = persistentSubcontarctorResources.getSourceCodeCollection();
            Collection<SourceCode> sourceCodeCollectionNew = subcontarctorResources.getSourceCodeCollection();
            List<String> illegalOrphanMessages = null;
            for (SourceCode sourceCodeCollectionOldSourceCode : sourceCodeCollectionOld) {
                if (!sourceCodeCollectionNew.contains(sourceCodeCollectionOldSourceCode)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain SourceCode " + sourceCodeCollectionOldSourceCode + " since its subcontResName field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (subcontractorNew != null) {
                subcontractorNew = em.getReference(subcontractorNew.getClass(), subcontractorNew.getSubId());
                subcontarctorResources.setSubcontractor(subcontractorNew);
            }
            Collection<SourceCode> attachedSourceCodeCollectionNew = new ArrayList<SourceCode>();
            for (SourceCode sourceCodeCollectionNewSourceCodeToAttach : sourceCodeCollectionNew) {
                sourceCodeCollectionNewSourceCodeToAttach = em.getReference(sourceCodeCollectionNewSourceCodeToAttach.getClass(), sourceCodeCollectionNewSourceCodeToAttach.getScId());
                attachedSourceCodeCollectionNew.add(sourceCodeCollectionNewSourceCodeToAttach);
            }
            sourceCodeCollectionNew = attachedSourceCodeCollectionNew;
            subcontarctorResources.setSourceCodeCollection(sourceCodeCollectionNew);
            subcontarctorResources = em.merge(subcontarctorResources);
            if (subcontractorOld != null && !subcontractorOld.equals(subcontractorNew)) {
                subcontractorOld.getSubcontarctorResourcesCollection().remove(subcontarctorResources);
                subcontractorOld = em.merge(subcontractorOld);
            }
            if (subcontractorNew != null && !subcontractorNew.equals(subcontractorOld)) {
                subcontractorNew.getSubcontarctorResourcesCollection().add(subcontarctorResources);
                subcontractorNew = em.merge(subcontractorNew);
            }
            for (SourceCode sourceCodeCollectionNewSourceCode : sourceCodeCollectionNew) {
                if (!sourceCodeCollectionOld.contains(sourceCodeCollectionNewSourceCode)) {
                    SubcontarctorResources oldSubcontResNameOfSourceCodeCollectionNewSourceCode = sourceCodeCollectionNewSourceCode.getSubcontResName();
                    sourceCodeCollectionNewSourceCode.setSubcontResName(subcontarctorResources);
                    sourceCodeCollectionNewSourceCode = em.merge(sourceCodeCollectionNewSourceCode);
                    if (oldSubcontResNameOfSourceCodeCollectionNewSourceCode != null && !oldSubcontResNameOfSourceCodeCollectionNewSourceCode.equals(subcontarctorResources)) {
                        oldSubcontResNameOfSourceCodeCollectionNewSourceCode.getSourceCodeCollection().remove(sourceCodeCollectionNewSourceCode);
                        oldSubcontResNameOfSourceCodeCollectionNewSourceCode = em.merge(oldSubcontResNameOfSourceCodeCollectionNewSourceCode);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = subcontarctorResources.getSubResId();
                if (findSubcontarctorResources(id) == null) {
                    throw new NonexistentEntityException("The subcontarctorResources with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            SubcontarctorResources subcontarctorResources;
            try {
                subcontarctorResources = em.getReference(SubcontarctorResources.class, id);
                subcontarctorResources.getSubResId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The subcontarctorResources with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<SourceCode> sourceCodeCollectionOrphanCheck = subcontarctorResources.getSourceCodeCollection();
            for (SourceCode sourceCodeCollectionOrphanCheckSourceCode : sourceCodeCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This SubcontarctorResources (" + subcontarctorResources + ") cannot be destroyed since the SourceCode " + sourceCodeCollectionOrphanCheckSourceCode + " in its sourceCodeCollection field has a non-nullable subcontResName field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Subcontarctors subcontractor = subcontarctorResources.getSubcontractor();
            if (subcontractor != null) {
                subcontractor.getSubcontarctorResourcesCollection().remove(subcontarctorResources);
                subcontractor = em.merge(subcontractor);
            }
            em.remove(subcontarctorResources);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<SubcontarctorResources> findSubcontarctorResourcesEntities() {
        return findSubcontarctorResourcesEntities(true, -1, -1);
    }

    public List<SubcontarctorResources> findSubcontarctorResourcesEntities(int maxResults, int firstResult) {
        return findSubcontarctorResourcesEntities(false, maxResults, firstResult);
    }

    private List<SubcontarctorResources> findSubcontarctorResourcesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(SubcontarctorResources.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public SubcontarctorResources findSubcontarctorResources(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(SubcontarctorResources.class, id);
        } finally {
            em.close();
        }
    }

    public int getSubcontarctorResourcesCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<SubcontarctorResources> rt = cq.from(SubcontarctorResources.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
